<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="操作时间" prop="actionTime">
        <el-date-picker v-model="dateRangeActionTime" type="datetimerange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期" placeholder="请选择操作时间" value-format="YYYY-MM-DD HH:mm:ss" :default-time="defaultTime"
          clearable>
        </el-date-picker>
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名" clearable style="width: 240px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
        <el-button icon="refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="danger" plain icon="delete" :disabled="multiple" @click="handleDelete"
          v-hasFunc="'signin:del'">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="download" @click="handleExport"
          v-hasFunc="'menu:export'">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" highlight-current-row
      @row-dblclick="handleView">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="日志ID" align="center" prop="id" :show-overflow-tooltip="true"
        v-if="columns.showColumn('id')">
        <template #default="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="用户ID" align="center" prop="userId" :show-overflow-tooltip="true" width="60"
        v-if="columns.showColumn('userId')">
        <template #default="scope">
          {{ scope.row.userId }}
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="userName" :show-overflow-tooltip="true" width="100"
        v-if="columns.showColumn('userName')">
        <template #default="scope">
          {{ scope.row.userName }}
        </template>
      </el-table-column>
      <el-table-column label="操作类型" align="center" prop="actionType" :show-overflow-tooltip="true"
        v-if="columns.showColumn('actionType')">
        <template #default="{ row }">
          <dict-tag :options="action_type" :value="row.actionType" />
        </template>
      </el-table-column>

      <el-table-column label="操作设备" align="center" prop="terminal" :show-overflow-tooltip="true"
        v-if="columns.showColumn('terminal')">
        <template #default="scope">
          <dict-tag :options="sys_login_terminal" :value="scope.row.terminal" />
        </template>
      </el-table-column>
      <el-table-column label="操作描述" align="center" prop="description" :show-overflow-tooltip="true"
        v-if="columns.showColumn('description')">
        <template #default="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column label="追踪ID" align="center" prop="traceIdentifier" :show-overflow-tooltip="true"
        v-if="columns.showColumn('traceIdentifier')">
        <template #default="scope">
          {{ scope.row.traceIdentifier }}
        </template>
      </el-table-column>
      <el-table-column label="操作时间" align="center" prop="actionTime" :show-overflow-tooltip="true"
        v-if="columns.showColumn('actionTime')">
        <template #default="scope">
          {{ parseTime(scope.row.actionTime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="primary" text icon="delete" @click="handleDelete(scope.row)"
            v-hasFunc="'signin:del'">删除</el-button>
          <el-button type="primary" text icon="view" @click="handleView(scope.row)"
            v-hasFunc="'signin:info'">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 详情信息 -->
    <el-drawer v-model="open" width="500px" title="详情信息" header-class="drawer-header">
      <el-descriptions title="基本信息" :column="1" border label-width="80" style="margin-bottom: 30px;">
        <el-descriptions-item label="操作人ID">{{ form.userId }}</el-descriptions-item>
        <el-descriptions-item label="操作人">{{ form.userName }}</el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ parseTime(form.actionTime) }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <dict-tag :options="action_type" :value="form.actionType" />
        </el-descriptions-item>
        <el-descriptions-item label="操作设备">
          <dict-tag :options="sys_login_terminal" :value="form.terminal" />
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="追踪信息" :column="1" border label-width="80">
        <el-descriptions-item label="追踪id">{{ form.traceInfo?.traceIdentifier }}</el-descriptions-item>
        <el-descriptions-item label="请求地址">{{ form.traceInfo?.url }}</el-descriptions-item>
        <el-descriptions-item label="请求时间">{{ parseTime(form.traceInfo?.requestTime) }}</el-descriptions-item>
        <el-descriptions-item label="响应时间">{{ parseTime(form.traceInfo?.responseTime) }}</el-descriptions-item>
        <el-descriptions-item label="耗时(ms)">{{ form.traceInfo?.duration }}</el-descriptions-item>
        <el-descriptions-item label="操作地址">{{ form.traceInfo?.clientIP }}</el-descriptions-item>
        <el-descriptions-item label="代理信息">{{ form.traceInfo?.userAgent }}</el-descriptions-item>
      </el-descriptions>

    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { listSessionLog, getSessionLog, delSessionLog, addSessionLog, updateSessionLog } from "@/api/log/sessionlog.js";

const { proxy } = getCurrentInstance()

//字典数据
const dicts = ["sys_login_terminal"];
const dictRefs = proxy.useDict(...dicts);
const { sys_login_terminal } = dictRefs;
const action_type = [{ label: '登录', value: 0, elTagType: 'tag', elTagClass: "success", themeClass: 'dark' }, { label: '注销', value: 1, elTagType: 'tag', elTagClass: "danger", themeClass: 'dark' }]

//弹窗操作类型
//0:新增，1：修改，2:查看
const operateType = ref(0)
//表单ref
const formRef = ref();
// 遮罩层
const loading = ref(true);
// 选中数组
const selected = ref([]);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 数据集
const dataList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);

//默认时间范围
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])

//定义操作时间查询参数
const dateRangeActionTime = ref([]);



// 查询参数
const queryParams = reactive({
  pageIndex: 1,
  pageSize: 10,
  sort: "actionTime",
  sortType: "desc",
  userName: undefined,
});



const state = reactive({
  single: true,
  multiple: true,
  form: {

  },
  rules: {
    customerId: [{ required: true, message: "客户id不能为空", trigger: "blur", type: "number" }],
    name: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
  },
  options: {
    // 商品种类 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    typeOptions: [],
  }
})

const { form, rules, options, single, multiple } = toRefs(state)


//所有列
const columns = ref([
  { visible: false, prop: 'id', label: '日志ID' },
  { visible: false, prop: 'userId', label: '用户ID' },
  { visible: true, prop: 'userName', label: '操作人' },
  { visible: true, prop: 'actionType', label: '操作类型' },
  { visible: true, prop: 'terminal', label: '操作设备' },
  { visible: true, prop: 'description', label: '操作描述' },
  { visible: true, prop: 'traceIdentifier', label: '追踪ID' },
  { visible: true, prop: 'actionTime', label: '操作时间' },
]);

// 获取列表方法
const getList = () => {
  loading.value = true;
  //添加时间范围参数
  proxy.addDateRange(queryParams, dateRangeActionTime.value, 'ActionTime');
  listSessionLog(queryParams).then((response) => {
    dataList.value = response.result;
    total.value = response.totalNum;
    loading.value = false;
  });
};

// 重置表单
const reset = () => {

};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageIndex = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  reset();
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selected.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 新增按钮操作
const handleAdd = () => {
  reset();
  operateType.value = 0;
  open.value = true;
  title.value = "添加数据";
};

// 修改按钮操作
const handleUpdate = (row) => {
  reset();
  operateType.value = 1;
  const key = row.id || selected.value;
  getSessionLog(key).then((response) => {
    Object.assign(form.value, response);
    open.value = true;
    title.value = "修改数据";
  });
};


//查看
const handleView = (row) => {
  reset();
  operateType.value = 2;
  var key = row.id;
  getSessionLog(key).then((response) => {
    Object.assign(form.value, response);
    open.value = true;
    title.value = "操作详情";
  });
}

// 提交按钮
const submitForm = () => {
  const validateForm = formRef.value?.validate;
  if (validateForm) {
    validateForm((valid) => {
      if (valid) {
        const apiCall = form.value.id ? updateSessionLog : addSessionLog;
        apiCall(form.value).then(() => {
          proxy.$modal.msgSuccess("操作成功");
          open.value = false;
          getList();
        });
      }
    });
  }
};

//取消弹窗
const cancel = () => {
  open.value = false;
  proxy.resetForm("form")
}

// 删除按钮操作
const handleDelete = (row) => {
  const keys = [].concat(row.id || selected.value);
  proxy.$modal.confirm("是否确认删除编号为" + keys + "的数据项？")
    .then(() => delSessionLog(keys))
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
};

// 导出按钮操作
const handleExport = () => {
  download("system//export", queryParams, `menu_${new Date().getTime()}.xlsx`);
};

// 页面加载时调用获取列表方法
onMounted(getList);
</script>

<style lang="scss" scoped>
:deep(.drawer-header) {
  margin: 0;
}
</style>
